<?php
namespace User\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use User\Model\User;
use Zend\Paginator\Paginator,
    Zend\Paginator\Adapter\Null as PageNull;
use User\Form\UserForm;

class UserController extends AbstractActionController
{
    protected $form;
    protected $storage;
    protected $authservice;
    protected $userTable;
    
    public function onDispatch( \Zend\Mvc\MvcEvent $e )
    {
        if (!$this->getAuthService()->hasIdentity()){
            return $this->redirect()->toRoute('home');
        }
        return parent::onDispatch( $e );
    }
    public function getUserTable()
    {
        if (!$this->userTable) {
            $sm = $this->getServiceLocator();
            $this->userTable = $sm->get('User\Model\UserTable');
        }
        return $this->userTable;
    }

    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()
            ->get('AuthService');
        }

        return $this->authservice;
    }

    public function indexAction()
    {
        $allRecord = $this->getUserTable()->countAll();
        $pageNull = new PageNull($allRecord);
        $itemsPerPage = 2;
        $pageRange = 5;
        $page = $this->params()->fromRoute('page', 1);
        var_dump($this->getEvent()->getRouteMatch()->getParam('id'));
        $offset = ($page - 1) * $itemsPerPage;
        $paginator = new Paginator($pageNull);
        $paginator->setCurrentPageNumber($page);
        $paginator->setItemCountPerPage($itemsPerPage);
        $paginator->setPageRange($pageRange);
        
        return new ViewModel(array(
            'user' => $this->getUserTable()->getList($offset, $itemsPerPage),
            'paginator' => $paginator,
            'allRecord' => $allRecord,
            'offset' => $offset,
            'itemsPerPage' => $itemsPerPage,
        ));
    }
    public function addAction()
    {
        $form = new UserForm();
        $form->get('submit')->setAttribute('value', 'Add');
        
        $request = $this->getRequest();
        if ($request->isPost()) {
            $album = new Album();
            $form->setInputFilter($album->getInputFilter());
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $album->exchangeArray($form->getData());
                $this->getAlbumTable()->saveAlbum($album);
        
                // Redirect to list of albums
                return $this->redirect()->toRoute('user');
            }
        }
        
        return array('form' => $form);
    }
    public function editAction()
    {
    
    }
    public function deleteAction()
    {
    
    }
}